﻿using MyBookReadsList.Data;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace MyBookReadsList.Validators
{
    class UsernameValidationRule : ValidationRule
    {
        private const int MinUsernameLength = 6;
        private const int MaxUsernameLength = 30;
        private const string ValidUsernameCharacters =
            "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890_.";

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null)
            {
                return new ValidationResult(false, "The Username field must contain a Username.");
            }
            else if (value.ToString().Length < MinUsernameLength)
            {
                string error = string.Format("The Username must be at least {0} characters long", MinUsernameLength);

                return new ValidationResult(false, error);
            }
            else if (value.ToString().Length > MaxUsernameLength)
            {
                string error = string.Format("The Username must be less than {0} characters long", MaxUsernameLength);
                return new ValidationResult(false, error);
            }
            else if (value.ToString().Any(ch => !ValidUsernameCharacters.Contains(ch)))
            {
                return new ValidationResult(false, "Username must contain only Latin letters, digits .,_");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }
}
